package com.example.springbootwebservice.client;

import com.example.springbootwebservice.interceptor.ClientInterceptor;
import com.example.springbootwebservice.service.DemoService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

/**
 * @author: xulinyi
 * @create: 2019-03-25 10:39
 **/
public class Cxfclient {
    // 服务端接口地址
    private static String address = "http://localhost:8080/webservice/ws?wsdl";

    public static void main(String[] args) {
        method1();
        method2();
    }
    /**
     * 方式1.代理类工厂方式,需要拿到对方的接口
     */
    public static void method1() {
        try {
            // 代理工厂
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            // 设置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
            // 添加用户信息验证
            jaxWsProxyFactoryBean.getOutInterceptors().add(
                    new ClientInterceptor("admin", "123456"));
            // 设置接口类型
            jaxWsProxyFactoryBean.setServiceClass(DemoService.class);
            // 创建一个代理接口实现
            DemoService ws = (DemoService) jaxWsProxyFactoryBean.create();
            // 调用代理接口的方法调用并返回结果
           String result = ws.say("lisi");
            System.out.println("代理类工厂方式返回结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 动态调用方式
     */
    public static void method2() {
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(address);
        // 添加用户信息验证
        client.getOutInterceptors().add(
                new ClientInterceptor("admin", "123456"));
        Object[] objects = new Object[0];
        try {
            // invoke("方法名",参数1,参数2,参数3....);
            objects = client.invoke("say", "zhangsan");
            System.out.println("动态调用方式结果:" + objects[0]);
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
    }

}